package com.team9.fitness.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * 回调注册服务
 * 用于管理异步回调，支持回调注册、执行和清理
 */
@Service
public class CallbackRegistryService {

    private static final Logger log = LoggerFactory.getLogger(CallbackRegistryService.class);

    // 存储回调函数的Map
    private final Map<String, Consumer<Map<String, Object>>> callbackRegistry = new ConcurrentHashMap<>();

    // 定时清理任务执行器
    private final ScheduledExecutorService cleanupExecutor = Executors.newScheduledThreadPool(1);

    /**
     * 注册回调函数
     * 
     * @param messageId      消息ID
     * @param callback       回调函数
     * @param timeoutSeconds 超时时间（秒）
     */
    public void registerCallback(String messageId, Consumer<Map<String, Object>> callback, int timeoutSeconds) {
        callbackRegistry.put(messageId, callback);

        // 设置定时清理任务，避免内存泄漏
        cleanupExecutor.schedule(() -> {
            if (callbackRegistry.remove(messageId) != null) {
                log.warn("回调超时，已清理: messageId={}", messageId);

                // 执行超时回调
                Map<String, Object> timeoutResult = new java.util.HashMap<>();
                timeoutResult.put("success", false);
                timeoutResult.put("message", "操作超时，请重试");
                timeoutResult.put("timeout", true);

                try {
                    callback.accept(timeoutResult);
                } catch (Exception e) {
                    log.error("执行超时回调失败: messageId={}", messageId, e);
                }
            }
        }, timeoutSeconds, TimeUnit.SECONDS);

        log.debug("注册回调: messageId={}, timeout={}s", messageId, timeoutSeconds);
    }

    /**
     * 执行回调函数
     * 
     * @param messageId 消息ID
     * @param result    处理结果
     * @return 是否成功执行回调
     */
    public boolean executeCallback(String messageId, Map<String, Object> result) {
        Consumer<Map<String, Object>> callback = callbackRegistry.remove(messageId);
        if (callback != null) {
            try {
                callback.accept(result);
                log.debug("执行回调成功: messageId={}", messageId);
                return true;
            } catch (Exception e) {
                log.error("执行回调失败: messageId={}", messageId, e);
                return false;
            }
        } else {
            log.warn("回调不存在: messageId={}", messageId);
            return false;
        }
    }

    /**
     * 检查回调是否存在
     * 
     * @param messageId 消息ID
     * @return 是否存在
     */
    public boolean hasCallback(String messageId) {
        return callbackRegistry.containsKey(messageId);
    }

    /**
     * 移除回调（不执行）
     * 
     * @param messageId 消息ID
     * @return 是否成功移除
     */
    public boolean removeCallback(String messageId) {
        return callbackRegistry.remove(messageId) != null;
    }

    /**
     * 获取当前注册的回调数量
     * 
     * @return 回调数量
     */
    public int getCallbackCount() {
        return callbackRegistry.size();
    }

    /**
     * 清理所有回调
     */
    public void clearAllCallbacks() {
        int count = callbackRegistry.size();
        callbackRegistry.clear();
        log.info("清理所有回调: count={}", count);
    }
}


